package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.LocationThread;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entitry.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user) {
        user.setCode(ValidateCodeUtils.generateValidateCode(6));
        log.info("---------------------------------------");
        log.info("登录i手机号：" + user.getPhone() + "----验证码：" + user.getCode());
        log.info("---------------------------------------");
//        request.getSession().setAttribute("checkUser", user);

        redisTemplate.opsForValue().set(user.getPhone(),user.getCode(),5, TimeUnit.MINUTES);

        return R.success("验证码发送成功！");
    }

    @PostMapping("/login")
    public R<String> login(@RequestBody User user,HttpServletRequest request) {

        Object code = redisTemplate.opsForValue().get(user.getPhone());
//        User checkUser = (User) session.getAttribute("checkUser");
//        if (checkUser.getPhone().equals(user.getPhone()) && checkUser.getCode().equals(user.getCode())) {
         if (user.getCode().equals(code)){
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone, user.getPhone());

            User one = userService.getOne(lqw);

            if (one == null) {
                userService.save(user);
            }
            LocationThread.setThreadData(user.getId());
            request.getSession().setAttribute("user", one);
            redisTemplate.delete(user.getPhone());
            return R.success("登陆成功");
        }
        return R.error("登录失败！");

    }

    @PostMapping("/loginout")
    public R logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
//        request.getSession().removeAttribute("checkUser");

        LocationThread.setThreadData(null);
        return R.success("退出成功！");
    }
}
